import { Button, Card, Col, Row, Image } from 'antd'
import Paragraph from 'antd/lib/typography/Paragraph'
import Title from 'antd/lib/typography/Title'
import { push } from 'connected-react-router'
import moment from 'moment'
import React, { FC } from 'react'
import { useDispatch } from 'react-redux'
import { Link } from 'react-router-dom'
import { API } from '../../config'
import { addCart } from '../../helpers/cart'
import { Product } from '../../models/product'

interface propsInterface {
  product: Product,
  showViewProduct?: boolean,
  showAddCartBtn?: boolean
}
const ProductItem: FC<propsInterface> = ({product,showViewProduct=true,showAddCartBtn=true}) => {
  const dispatch = useDispatch()
  const addToCart = () => {
    addCart(product,()=>{
      dispatch(push('/cart'))
    })
    
  }
  const showButtons = () => {
    const buttonArray = []
    if(showViewProduct) {
      buttonArray.push(<Button type="link"><Link to={`/product/${product._id}`}>查看详情</Link></Button>)
    }
    if(showAddCartBtn) {
      buttonArray.push(<Button type="link" onClick={addToCart}>加入购物车</Button>)
    }
    return buttonArray
  }
  return (
    <div>

      <Card
        hoverable
        style={{ width: 240 }}
        // cover={
        //   <Image src={`${API}/product/photo/${product._id}`} alt={product.name} />
        // }
        actions={showButtons()}
      >
        <Title level={5}>
          {product.name}
      </Title>
        <Paragraph ellipsis={{ rows: 2 }}>{product.description}</Paragraph>
        <Row>
          <Col span="12">
            销量：{product.sold}
        </Col>
          <Col span="12" style={{ textAlign: 'right' }}>
            价格：{product.price}
        </Col>
        </Row>
        <Row>
          <Col span="12">
            上架时间：{moment(product.createdAt).format('YYYY-MM-DD')}
        </Col>
          <Col span="12" style={{ textAlign: 'right' }}>
            所属分类：{product.category && product.category.name}
        </Col>
        </Row>
      </Card>

    </div>
  )
}
export default ProductItem